package com.imooc.queue;

/**
 * 链表实现的队列
 */
public class LinkedListQueue<E> implements Queue<E> {

    private class Node{
        private E e;
        private Node next;

        public Node(E e, Node next) {
            this.e = e;
            this.next = next;
        }
        public Node(E e) {
            this.e = e;
            this.next = null;
        }
        public Node() {
            this.e = null;
            this.next = null;
        }

        @Override
        public String toString() {
            return e.toString();
        }
    }

    /**
     * 由于末端元素不适合取值，但适合添加值，所以末端做队尾
     * 首端做队首
     */
    private Node head, tail;
    private int size;

    public LinkedListQueue() {
        this.head = null;
        this.tail = null;
        this.size = 0;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void enqueue(E e) {
        if(head == null) {
            head = new Node(e);
            tail = head;
        }else {
            tail.next = new Node(e);
            tail = tail.next;
        }
        size++;
    }

    @Override
    public E dequeue() {
        if(isEmpty()) {
            throw new IllegalArgumentException("Dequeue failed. Queue is empty.");
        }
        Node delNode = head;
        head = head.next;
        delNode.next = null;
        if(head == null)
            tail = null;
        size--;
        return delNode.e;
    }

    @Override
    public E getFront() {
        if(isEmpty()) {
            throw new IllegalArgumentException("Get failed. Queue is empty.");
        }
        return head.e;
    }
}
